<script>
import nzh from 'nzh'
import AmountInput from '@/components/amountInput/index'
import Album from '@/components/Album/albumWithUpload.vue'
import ImageWithUpload from '@/components/ImageWithUpload/default'
import dayjs from 'dayjs'
import { register } from '@/api/company'
import { verificationcodeSend } from '@/api/basic'
export default {
  components: {
    AmountInput,
    Album,
    ImageWithUpload
  },
  data() {
    return {
      isMobile: false,
      isSubmitting: false,
      autoCompletion: true,
      styles: {
        height: '100px',
        width: '100px',
        borderRadius: '6px',
        border: 'none'
      },
      currentStep: 0,
      sendCodeBtn: {
        interval: 60,
        delay: 0,
        timer: null,
        count: 0
      },
      form: {
        companyName: '',
        businessLicenseCode: '',
        businessLicenseBeginDate: null,
        businessLicenseEndDate: null,
        registeredCapital: null,
        verification_code: '',
        verification_key: '',
        adminAccount: '',
        adminAccountPassword: '',
        duplicatePassword: '',
        registeredAddress: '',
        businessLicense: [],
        companyImages: [],
        abbreviation: ''
      },
      formRules: {
        companyName: [
          {
            type: 'string',
            required: true,
            message: '请填写公司名称',
            trigger: ['change', 'blur']
          }
        ],
        businessLicenseCode: [
          {
            type: 'string',
            required: true,
            message: '请填写营业执照号',
            trigger: ['change', 'blur']
          }
        ],
        businessLicenseBeginDate: [
          {
            validator: (rule, value, callback) => {
              if (!(value instanceof Date)) {
                return callback(new Error('请选择营业执照起始日期'))
              }

              if (this.form.businessLicenseEndDate instanceof Date) {
                if (
                  value.getTime() >= this.form.businessLicenseEndDate.getTime()
                ) {
                  return callback(
                    new Error('营业执照的起始日期必须小于截至日期')
                  )
                }
              }

              callback()
            },
            required: true,
            trigger: ['change', 'blur']
          }
        ],
        businessLicenseEndDate: [
          {
            validator: (rule, value, callback) => {
              if (!(value instanceof Date)) {
                console.log(value, 'value')
                return callback(new Error('请选择营业执照截至日期'))
              }

              if (this.form.businessLicenseBeginDate instanceof Date) {
                if (
                  value.getTime() <=
                  this.form.businessLicenseBeginDate.getTime()
                ) {
                  return callback(
                    new Error('营业执照的截至日期必须大于起始日期')
                  )
                }
              }

              callback()
            },
            required: true,
            trigger: ['change', 'blur']
          }
        ],
        registeredCapital: [
          {
            required: true,
            message: '请填写注册资金',
            trigger: ['change', 'blur']
          }
        ],

        adminAccount: [
          {
            type: 'string',
            required: true,
            message: '请填写管理员账号',
            trigger: ['change', 'blur']
          }
        ],
        adminAccountPassword: [
          {
            type: 'string',
            required: true,
            message: '请填写管理员密码',
            trigger: ['change', 'blur']
          },
          {
            pattern: /^[a-zA-Z0-9_.]{6,20}$/,
            message: '密码只能包含数字、英文字符、点（.）和下划线（_），长度为6位至20位',
            trigger: ['change', 'blur']
          }
        ],
        duplicatePassword: [
          {
            validator: (rule, value, callback) => {
              if (typeof value !== 'string' || value === '') {
                return callback(new Error('请填写重复密码'))
              }

              if (value !== this.form.adminAccountPassword) {
                return callback(new Error('两次密码不一致'))
              }

              callback()
            },
            required: true,
            trigger: ['change', 'blur']
          }
        ],
        registeredAddress: [
          {
            type: 'string',
            required: true,
            message: '请填写注册地址',
            trigger: ['change', 'blur']
          }
        ],
        businessLicense: [
          {
            type: 'string',
            required: true,
            message: '请上传营业执照',
            trigger: ['change', 'blur']
          }
        ],
        verification_code: [
          {
            type: 'string',
            required: true,
            message: '请输入验证码',
            trigger: ['change', 'blur']
          },
          { min: 4, max: 4, message: '请输入正确的验证码', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    data() {
      if (!this.autoCompletion) return {}

      return {
        analysis: 1,
        type: 'recognition'
      }
    },
    businessLicenseEndDateFormat() {
      const { businessLicenseEndDate } = this.form
      if (!(businessLicenseEndDate instanceof Date)) return 'yyyy-MM-dd'

      if (dayjs(businessLicenseEndDate).isBefore('2099-01-01', 'day')) {
        return 'yyyy-MM-dd'
      }

      return '长期'
    },
    sendCodeBtnText() {
      const { delay } = this.sendCodeBtn
      if (delay > 0) return `${delay}秒后重发`

      return '发送验证码'
    },
    sendCodeBtnDisabled() {
      const { delay } = this.sendCodeBtn
      return delay > 0
    }
  },
  watch: {
    form: {
      handler(v) {},
      deep: true
    },
    'form.businessLicense': function() {
      this.validateField('businessLicense')
    }
  },
  created() {
    this._isMobile()
  },
  methods: {
    toLoginPage() {
      this.$router.push('/login')
    },
    toExaminePage() {
      this.$router.push('/company/examine')
    },
    _isMobile() {
      const flag = navigator.userAgent.match(
        /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i
      )
      if (flag) {
        this.isMobile = true
      } else {
        this.isMobile = false
      }

      console.log('flag ------>', flag)
      // return flag
    },
    destoryTimer() {
      const { timer } = this.sendCodeBtn
      if (typeof timer === 'number' && !isNaN(timer)) clearInterval(timer)
    },
    startSendCodeTimer() {
      if (this.sendCodeBtnDisabled) return

      this.sendCodeBtn.delay = this.sendCodeBtn.interval
      this.sendCodeBtn.timer = setInterval(() => {
        console.log('hahaha')
        const { timer, delay } = this.sendCodeBtn

        if (delay <= 0 && typeof timer === 'number' && !isNaN(timer)) {
          clearInterval(timer)
          return
        }

        this.sendCodeBtn.delay--
      }, 1000)
    },
    handleBusinessLiceneAnalysis(data) {
      console.log(data, '我识别出来了')
      if (!this.autoCompletion) return
      const result = data?.data?.analysis?.result
      console.log(result, 'result')
      if (!result) return

      if (typeof result.name === 'string') this.form.companyName = result.name

      if (typeof result.found_date === 'string') {
        const d = result.found_date
          .replaceAll('年', '-')
          .replaceAll('月', '-')
          .replaceAll('日', '')
        console.log(d, 'date')
        const date = dayjs(d).toDate()
        if (!isNaN(date.getTime())) this.form.businessLicenseBeginDate = date
      }
      // if (typeof result.business_term === 'string') {
      //   this.form.businessLicenseEndDate=result.issue_date
      //   const location = result.business_term.indexOf('至')
      //   const expiration = result.business_term.substr(location + 1, '11')
      //   const d = expiration
      //     .replaceAll('年', '-')
      //     .replaceAll('月', '-')
      //     .replaceAll('日', '')
      //   const date = dayjs(d).toDate()
      //   if (!isNaN(date.getTime())) this.form.businessLicenseEndDate = '长期'
      // }

      if (
        typeof result.registered_capital === 'string' &&
        result.registered_capital !== ''
      ) {
        this.form.registeredCapital = result.registered_capital
      }

      if (
        typeof result.business_term === 'string' ||
        typeof result.issue_date === 'string'
      ) {
        if (typeof result.issue_date === 'string' && result.issue_date !== '') {
          this.form.businessLicenseEndDate = dayjs(result.issue_date).toDate()
        }
        // else {
        //   this.form.businessLicenseEndDate = dayjs('2099-01-01').toDate()
        // }
        // else if (result.business_term.includes('至长期')) {
        //   this.form.businessLicenseEndDate = dayjs('2099-01-01').toDate()
        // }
      }

      if (typeof result.registration_number === 'string') {
        this.form.businessLicenseCode = result.registration_number
      }
    },
    validateField(field) {
      this.$refs.form?.validateField?.(field)
    },
    buildParams() {
      const {
        companyName,
        businessLicenseCode,
        businessLicenseBeginDate,
        businessLicenseEndDate,
        registeredCapital,
        verification_code,
        verification_key,
        adminAccount,
        adminAccountPassword,
        registeredAddress,
        businessLicense,
        companyImages,
        abbreviation
      } = this.form
      return {
        licNo: businessLicenseCode,
        licName: companyName,
        businessLicensePath: businessLicense,
        licAddress: registeredAddress,
        licRegCapital: registeredCapital,
        licFoundDate: dayjs(businessLicenseBeginDate).format('YYYY-MM-DD'),
        licEndDate: dayjs(businessLicenseEndDate).format('YYYY-MM-DD'),
        phone: adminAccount,
        password: adminAccountPassword,
        verification_code: verification_code,
        verification_key: verification_key,
        company_images: JSON.stringify(companyImages),
        abbreviation
      }
    },
    sleep(t) {
      return new Promise((r) => setTimeout(r, t))
    },
    submit() {
      this.$refs.form?.validate?.(async(flag) => {
        try {
          if (this.isSubmitting) return
          if (!flag) return

          this.isSubmitting = true

          await this.sleep(300)
          const params = this.buildParams()

          const result = await register(params)
          console.log(result)
          this.isSubmitting = false

          if (result.code !== 200) {
            throw new Error(result.message ?? '注册失败')
          }

          this.$message.success(result.message ?? '提交成功 等待审核')
          this.$router.push('/prompt')
        } catch (e) {
          console.log('我来了')
          this.isSubmitting = false
          this.$message.error(e.response.data.message)
        }
      })
    },

    checkPhoneIsNotEmpty() {
      return new Promise((resolve, reject) => {
        this.$refs.form.validateField('adminAccount', (e) => {
          if (e) resolve(false)
          else resolve(true)
        })
      })

      // return !!this.form.adminAccount
    },

    async sendCode() {
      const isEmpty = await this.checkPhoneIsNotEmpty()

      if (!isEmpty) return this.$message.error('请填写手机号')

      if (this.sendCodeBtnDisabled) return

      this.startSendCodeTimer()

      const z_reg =
        /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/
      if (!z_reg.test(this.form.adminAccount)) {
        return this.$message({
          showClose: true,
          message: '请输入正确的手机号',
          type: 'error'
        })
      }

      const data = {
        phone: this.form.adminAccount
      }
      verificationcodeSend(data)
        .then((res) => {
          console.log(res)
          this.form.verification_key = res.data.key
          this.$message({
            showClose: true,
            message: '发送成功',
            type: 'success'
          })
        })
        .catch((err) => {
          this.$message({
            showClose: true,
            message: err?.response?.data?.message,
            type: 'error'
          })
        })
    },
    beforeDestroy() {
      this.destoryTimer()
    },

    uploadCompanyPhotoSuccess(e) {
      this.form.companyImages.push(e.data.path)
    },

    uploadCompanyPhotoExceed(e) {
      this.$message.error('最多可上传3张公司照片')
    },

    onBeforeRemoveCompanyPhoto(e) {
      return new Promise((resolve, reject) => {
        this.$confirm('是否删除该张图片', '提示', {
          cancelButtonText: '取消',
          confirmButtonText: '确定',
          type: 'warning'
        }).then(() => {
          resolve()
        }).catch(() => {
          reject()
        })
      })
    },

    onCompanyPhotoRemove(e) {
      this.form.companyImages = this.form.companyImages.filter(item => item !== e.url)
    }
  }
}
</script>

<template>
  <div class="company-register-container">
    <div class="navigation">
      <div class="logo-container">
        <img class="logo" src="https://obs-user-test.obs.cn-east-3.myhuaweicloud.com:443/logo/test_1685699935_9z2SDQ5UcZ.png">
        <span class="sep-line" />
        <span class="title">企业注册</span>
      </div>
      <div class="login">
        <span style="color: #333333;">已有账号？</span>
        <span style="color: #2F88FF;cursor: pointer;" @click="toLoginPage">请登录</span>
      </div>
    </div>

    <el-row type="flex" justify="center">
      <el-col :xs="16" :sm="12" :md="10" :lg="9" :xl="6">
        <div style="margin-bottom: 60px;">
          <el-steps :active="currentStep" align-center>
            <el-step title="填写信息" />
            <el-step title="提交审核" />
          </el-steps>
        </div>
        <el-form
          ref="form"
          :label-width="isMobile ? '' : '160px'"
          :label-position="isMobile ? 'top' : 'right'"
          :model="form"
          :rules="formRules"
          :disabled="isSubmitting"
        >
          <el-form-item label="手机号" prop="adminAccount">
            <el-input v-model="form.adminAccount" placeholder="请填写手机号" />
          </el-form-item>

          <el-form-item label="验证码" prop="verification_code">
            <div class="" style="display: flex">
              <el-input
                v-model="form.verification_code"
                placeholder="请填写验证码"
              />

              <el-button
                :disabled="sendCodeBtnDisabled"
                style="margin-left: 16px;border-radius: 6px;color: #8e8e8e;"
                @click="sendCode"
              >
                {{ sendCodeBtnText }}
              </el-button>
            </div>
          </el-form-item>

          <el-form-item label="密码" prop="adminAccountPassword">
            <el-input
              v-model="form.adminAccountPassword"
              type="password"
              placeholder="请填写密码"
              auto-complete="new-password"
            />
          </el-form-item>

          <el-form-item label="再次确认密码" prop="duplicatePassword">
            <el-input
              v-model="form.duplicatePassword"
              type="password"
              placeholder="请填写再次确认密码"
              auto-complete="new-password"
            />
          </el-form-item>

          <el-form-item label="营业执照" prop="businessLicense">
            <ImageWithUpload
              v-model="form.businessLicense"
              :style="styles"
              :data="data"
              @success="handleBusinessLiceneAnalysis"
            />
            <el-switch
              v-model="autoCompletion"
              style="display: block; margin-top: 14px"
              active-color="#13ce66"
              inactive-color="#d0d0d0"
              active-text="自动识别营业执照"
            />
          </el-form-item>

          <el-form-item label="公司名称" prop="companyName">
            <el-input v-model="form.companyName" placeholder="请填写公司名称" />
          </el-form-item>

          <el-form-item label="营业执照号" prop="businessLicenseCode">
            <el-input v-model="form.businessLicenseCode" placeholder="营业执照号" />
          </el-form-item>
          <el-form-item label="营业执照注册资金" prop="registeredCapital">
            <el-input
              v-model="form.registeredCapital"
              placeholder="营业执照注册资金"
            />
          </el-form-item>
          <el-form-item label="营业执照成立日期" prop="businessLicenseBeginDate">
            <el-date-picker
              v-model="form.businessLicenseBeginDate"
              style="width: 100%"
              type="date"
              placeholder="选择营业执照成立日期"
            />
          </el-form-item>
          <el-form-item label="营业执照到期时间" prop="businessLicenseEndDate">
            <el-date-picker
              v-model="form.businessLicenseEndDate"
              style="width: 100%"
              type="date"
              placeholder="请填写营业执照到期时间"
              :format="businessLicenseEndDateFormat"
            />
          </el-form-item>

          <el-form-item label="公司注册地址" prop="registeredAddress">
            <el-input
              v-model="form.registeredAddress"
              type="text"
              placeholder="请填写公司注册地址"
            />
          </el-form-item>

          <el-form-item label="公司名简称" prop="abbreviation">
            <el-input v-model="form.abbreviation" placeholder="请填写公司简称" />
          </el-form-item>

          <el-form-item label="公司介绍" prop="introduction">
            <el-input
              v-model="form.introduction"
              placeholder="请填写公司介绍"
              type="textarea"
              :autosize="{ minRows: 4, maxRows: 6 }"
            />
          </el-form-item>

          <el-form-item label="公司照片" prop="companyImages">
            <el-upload
              action="/api/v1/upload/file"
              list-type="picture-card"
              :on-success="uploadCompanyPhotoSuccess"
              :limit="3"
              accept=".jpg,.jpeg,.png"
              :on-exceed="uploadCompanyPhotoExceed"
              :before-remove="onBeforeRemoveCompanyPhoto"
              :on-remove="onCompanyPhotoRemove"
            >
              <i class="el-icon-plus" />
            </el-upload>
          </el-form-item>

          <el-form-item style="text-align: center;">
            <el-button
              style="border-radius: 2px;"
              @click="toLoginPage"
            >
              返回
            </el-button>

            <el-button
              style="border-radius: 2px;"
              type="primary"
              :disabled="isSubmitting"
              :loading="isSubmitting"
              @click="submit"
            >
              提交审核
            </el-button>
          </el-form-item>

        </el-form>
      </el-col>
    </el-row>

  </div>
</template>

<style lang="scss">
.company-register-container {
  background-color: #fff;
  .navigation {
    box-shadow: 0px 1px 2px 0px rgba(158,158,158,0.16);
    padding: 20px 220px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 80px;
    .logo-container {
      display: flex;
      align-items: center;
      .logo {
        width: 184px;
      }
      .sep-line {
        margin: 0 10px;
        background-color: #DCDFE6;
        width: 1px;
        height: 44px;
      }
      .title {
        color: #333;
        font-size: 26px;
      }
    }
  }
  @media screen and (max-width: 979px){
    .navigation {
      box-shadow: 0px 1px 2px 0px rgba(158,158,158,0.16);
      padding: 7% 2%;
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 5%;
      .logo-container {
        display: flex;
        align-items: center;
        .logo {
          width: 130px;
        }
        .sep-line {
          margin: 0 10px;
          background-color: #DCDFE6;
          width: 1px;
          height: 44px;
        }
        .title {
          color: #333;
          font-size: 20px;
        }
      }
      .login{
        font-size: 14px;
      }
    }
  }

  .el-steps.el-steps--horizontal {
    .is-wait {
      .el-step__icon.is-text {
        background-color: #BBBBBB;
      }
    }
    .el-step__line {
      height: 0;
      border: 1px dashed #DCDFE6;
      background-color: unset;
    }
    .el-step__icon.is-text {
      border: none;
      color: white;
      background-color: #2F88FF;
      .el-step__main {
        .el-step__title {
          color: #333333;
          font-size: 15px !important;
          font-weight: normal;

        }
      }
    }
  }

  .el-form {
    .el-form-item__label {
      color: #333;
      font-size: 15px;
      padding-right: 30px;
      font-weight: bold;
    }
    .el-input__inner {
      border-radius: 6px;
      border-color: #DCDFE6;
      &::placeholder {
        color: #BBBBBB;
      }
    }

  }

}

</style>
